#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time       :   21:19
# Author     : Y4
# Site       : 
# File       : 009 线程的全局变量 -线程同步.py
# Software   : PyCharm


import threading
import os

lock = threading.Lock()


n = 0
def run1():
    # 获取线程锁,如果已经上锁,则等待锁的释放
    lock.acquire()      # 阻塞

    global n
    for i in range(1000000):
        n += 1
        print('{}--{}'.format(n, os.getpid()))

    lock.release()

def run2():
    # 获取线程锁,如果已经上锁,则等待锁的释放
    lock.acquire()  # 阻塞

    global n
    for i in range(1000000):
        n += 1
        print('{}--{}'.format(n,os.getpid()))

    lock.release()

if __name__ == '__main__':
    t = threading.Thread(target=run1)
    t1 = threading.Thread(target=run2)

    t.start()
    t1.start()

    t.join()
    t1.join()

    print(n)                    # 不加lock 1442355
                                # 加 2000000